<template>
  <div v-html="processedMarkdown"></div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import container from 'markdown-it-container'
import * as XLSX from 'xlsx'
import 'highlight.js/styles/github.css'

// 初始化 Markdown 解析器
const md = new MarkdownIt({
  html: true,
  breaks: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value
      } catch (e) {
        console.error(e)
      }
    }
    return escapeHtml(str)
  }
})

// 自定义容器（可选）
md.use(container, 'image-describe', {
  render: function (tokens, idx) {
    return tokens[idx].nesting === 1 ? '<image-describe>' : '</image-describe>'
  }
})

// 转义 HTML 防止 XSS
function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;')
}

// 处理 HTML 内容：添加代码块包装 + 表格识别和下载功能
function processMarkdownHtml(html) {
  const temp = document.createElement('div')
  temp.innerHTML = html

  const tables = temp.querySelectorAll('table')
  tables.forEach((table, index) => {
    // 提取原始数据用于下载
    const rows = Array.from(table.rows)
    const originalData = rows.map(row =>
      Array.from(row.cells).map(cell => ({
        value: cell.textContent.trim(),
        colspan: cell.colSpan > 1 ? cell.colSpan : null,
        rowspan: cell.rowSpan > 1 ? cell.rowSpan : null
      }))
    )

    // 创建容器
    const wrapper = document.createElement('div')
    wrapper.className = 'markdown-table-wrapper'
    wrapper.style.minWidth = '800px' // 设置最小宽度保持一致性

    // 添加标题和下载按钮
    wrapper.innerHTML = `
      <div class="table-header">
        <span class="table-title">表格</span>
        <span class="download-icon" title="下载表格" data-table-id="${index}">
          <i class="bi bi-download">📥</i>
        </span>
      </div>
    `

    // 存储原始数据到全局对象中
    if (!window.tableDataStore) window.tableDataStore = {}
    window.tableDataStore[`table-${index}`] = originalData

    // 替换 DOM 结构
    wrapper.appendChild(table.cloneNode(true))
    table.parentNode.replaceChild(wrapper, table)
  })

  return temp.innerHTML
}

// 下载 Excel 文件函数
function handleDownloadTable(data) {
  const ws = XLSX.utils.json_to_sheet([])
  const merges = []

  // 将数据转换为二维数组
  const dataArray = data.map(row => row.map(cell => cell.value))

  // 处理合并单元格
  data.forEach((row, rowIndex) => {
    row.forEach((cell, colIndex) => {
      if (cell.colspan || cell.rowspan) {
        merges.push({
          s: { r: rowIndex, c: colIndex },
          e: { r: rowIndex + (cell.rowspan || 1) - 1, c: colIndex + (cell.colspan || 1) - 1 }
        })
      }
    })
  })

  // 添加数据到工作表
  XLSX.utils.sheet_add_aoa(ws, dataArray, { origin: 'A1' })

  // 设置合并单元格
  if (merges.length) {
    ws['!merges'] = merges
  }

  // 创建工作簿并添加工作表
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 生成Excel文件并触发下载
  XLSX.writeFile(wb, 'table_data.xlsx')
}

const processedMarkdown = ref('')

onMounted(() => {
  const markdownContent = `
# 示例文档

这是一个 JSON 代码块：

\`\`\`json
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
\`\`\`

<table>
  <tr><th colspan="2">井别</th><th>开发井</th><th>井型</th><th>水平井</th></tr>
  <tr><td colspan="2">目标层位</td><td>灯四段</td><td>管柱下深（m）</td><td>6354.93</td></tr>
  <tr><td colspan="2">井下安全阀下深（m）</td><td>87.73</td><td>封隔器下深（m）</td><td>5147.33</td></tr>
  <tr><td colspan="2">地层压力（MPa）</td><td>56.19</td><td>地层温度（℃）</td><td>149.9</td></tr>
  <tr><td colspan="2">H2S含量（g/m3）</td><td>9.22</td><td>CO2含量（g/m3）</td><td>0</td></tr>
  <tr><td colspan="2">日产量（×104/m3）</td><td>59.97</td><td>稳定油压（MPa）</td><td>29.2</td></tr>
  <tr><td colspan="4">备注信息</td></tr>
</table>
  `

  const html = md.render(markdownContent)
  processedMarkdown.value = processMarkdownHtml(html)

  // 在 DOM 更新后绑定点击事件
  nextTick(() => {
    const downloadIcons = document.querySelectorAll('.download-icon')
    downloadIcons.forEach(icon => {
      icon.addEventListener('click', () => {
        const tableId = icon.getAttribute('data-table-id')
        const originalData = window.tableDataStore[`table-${tableId}`]
        if (originalData) {
          handleDownloadTable(originalData)
        }
      })
    })
  })
})
</script>
<style>
.download-icon {
  cursor: pointer;
  font-size: 16px;
  color: #666;
  transition: color 0.2s ease;
  margin-left: 10px;
}
.download-icon:hover {
  color: #007bff;
}

.markdown-table-wrapper {
  margin: 1rem auto;
  border: 1px solid #e4e4e4;
  border-radius: 8px;
  background-color: #fff;
  overflow-x: auto; /* 启用横向滚动 */
  -webkit-overflow-scrolling: touch; /* 移动端平滑滚动 */
  min-width: 500px; /* 最小宽度为 500px */
  width: 100%; /* 宽度占满容器 */
  max-width: 100%; /* 不超出父级容器 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  position: relative; /* 配合滚动提示使用 */
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #eeeeee;
  padding: 6px 12px;
  font-size: 14px;
  color: #535353;
  border-bottom: 1px solid #ddd;
}

.table-title {
  font-weight: bold;
  font-size: 16px;
  color: #000;
}

.markdown-table-wrapper table {
  min-width: 800px;
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  font-size: 14px;
  color: #333;
  border: 1px solid #ccc;
}

.markdown-table-wrapper table td,
.markdown-table-wrapper table th {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
  overflow: hidden;
  white-space: nowrap;
  word-break: keep-all;
}

.markdown-table-wrapper table .header-row th {
  background-color: #f6f6f6;
  color: #333;
  font-weight: bold;
  border: 1px solid #ccc;
}
</style>